package com.burt.zookeeper.javaapi.lock;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * Description:
 * User: Burt
 * Date: 2017-08-11 Time: 11:37
 */
public class ZookeeperClient {
    private final static String CONNECTSTRING = "192.168.0.8:2181,192.168.0.7:2181," +
            "192.168.0.9:2181";

    private static final  int sessionTimeOut = 5000;

    public static ZooKeeper getInstance() {

        CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = null;
        try {
            zooKeeper = new ZooKeeper(CONNECTSTRING, sessionTimeOut, watchedEvent -> {
                if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
                    countDownLatch.countDown();
                }
            });

            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return zooKeeper;

    }

    public static int getSessionTimeOut() {
        return sessionTimeOut;
    }
}
